// pages/ShippingCart/ShippingCart.js
const app = getApp()
import {
  queryUserShippingCart,
  deleteShippingCart,
  updateCartItemQuantity,
  queryDiscountProducts,
  removeShippingCartToFavorite
} from "../../service/shipping-cart"
import {
  queryDefaultDeliveryAddress
} from "../../service/delivery-address"
import Decimal from 'decimal.js';
import Toast from '@vant/weapp/toast/toast';
import {
  buildQueryString
} from "../../utils/url"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 胶囊距离屏幕顶部的距离
    top: app.globalData.menuButtonTop,
    // 胶囊高度
    height: app.globalData.menuButtonHeight,
    // 胶囊左方大小
    left: app.globalData.menuButtonLeft,
    // 胶囊底部距离屏幕顶部的距离
    bottom: app.globalData.menuButtonBottom,
    // 购物车列表
    shippingCartList: [],
    // 购物车是否选中的列表
    shippingCartSelectedList: [],
    // 收货地址
    deliverAddress: null,
    // 选择全部购物车商品Or降价购物车商品（0-全部，1-降价）
    activeIndex: 0,
    // 购物车状态（0-结算，1-编辑）
    shippingCartStatus: 0,
    // 是否全选状态
    selectAll: false,
    // 已选择的商品的信息
    selectedProductInfo: {
      // 已选择商品的总价
      totalPrice: 0,
      // 已选择商品的总种类
      types: 0,
      // 已选择商品的总件数
      pieces: 0,
    },
    // 控制 scroll-view 下拉刷新状态的变量
    isRefreshing: false
  },
  /**
   * 下拉刷新处理函数
   */
  async onRefresh() {
    // 加载购物车数据
    const index = this.data.activeIndex
    if (index === 0) {
      // 请求全部购物车数据
      await this.loadShippingCartList("all")
    } else {
      // 请求降价的购物车数据
      await this.loadShippingCartList("discount")
    }
    this.setData({
      selectAll: false,
      isRefreshing: false
    })
  },
  /**
   * 点击添加收货地址
   */
  onTapAddDeliveryAddress() {
    wx.navigateTo({
      url: '/pages/DeliveryAddress/AddDeliveryAddress/AddDeliveryAddress',
    })
  },
  /**
   * 点击购物车的复选框
   */
  onTapShippingCartCheckbox(event) {
    const flag = event.detail
    const index = event.currentTarget.dataset.index
    this.setData({
      [`shippingCartSelectedList[${index}]`]: flag
    })
    if (this.allTrue(this.data.shippingCartSelectedList)) {
      this.setData({
        selectAll: true
      })
    } else {
      this.setData({
        selectAll: false
      })
    }
    // 更改
    const selectedShippingCartList = this.data.shippingCartList.filter((cart, index) => {
      return this.data.shippingCartSelectedList[index] === true
    })
    const calculateRes = selectedShippingCartList.reduce((accumulator, currentItem) => {
      accumulator.totalQuantity += currentItem.quantity;
      accumulator.totalPrice += currentItem.discountPrice * currentItem.quantity;
      return accumulator;
    }, {
      totalQuantity: 0,
      totalPrice: 0
    })
    calculateRes.totalPrice = calculateRes.totalPrice.toFixed(2)
    this.setData({
      "selectedProductInfo.totalPrice": calculateRes.totalPrice,
      "selectedProductInfo.types": selectedShippingCartList.length,
      "selectedProductInfo.pieces": calculateRes.totalQuantity
    })
  },
  /**
   *  点击跳转到首页
   */
  onTapSwitchToHomePage() {
    wx.switchTab({
      url: '/pages/HomePage/HomePage',
    })
  },
  /**
   * 点击跳转到购物车页面
   */
  onTapAddressInformation() {
    wx.navigateTo({
      url: '/pages/DeliveryAddress/DeliveryAddress',
    })
  },
  /**
   * 点击移入收藏按钮
   */
  async onTapRemoveToCollcetion() {
    const selectedShippingCartIds = this.data.shippingCartList.filter((cart, index) => {
      return this.data.shippingCartSelectedList[index] === true;
    }).map(cart => cart.id);
    if (selectedShippingCartIds.length === 0) {
      wx.showToast({
        title: '请选择需要移入收藏的商品！',
        icon: "none"
      })
      return
    }
    const that = this
    wx.showModal({
      title: '提示',
      content: '确定要将选择的商品移入收藏吗？',
      complete: async (res) => {
        if (res.cancel) { }
        if (res.confirm) {
          await removeShippingCartToFavorite(selectedShippingCartIds)
          // 加载购物车数据
          const index = that.data.activeIndex
          if (index === 0) {
            // 请求全部购物车数据
            await that.loadShippingCartList("all")
          } else {
            // 请求降价的购物车数据
            await that.loadShippingCartList("discount")
          }
          if (this.data.shippingCartSelectedList.length === 0) {
            this.setData({
              selectAll: false
            })
          }
        }
      }
    })
  },
  /**
   * 点击删除按钮
   */
  onTapDeleteButton() {
    console.log("点击删除按钮");
    // 首先筛选出所有的商品
    const selectedShippingCartIds = this.data.shippingCartList.filter((cart, index) => {
      return this.data.shippingCartSelectedList[index] === true;
    }).map(cart => cart.id);
    if (selectedShippingCartIds.length === 0) {
      wx.showToast({
        title: '请选择需要删除的商品！',
        icon: "none"
      })
      return
    }
    const that = this
    wx.showModal({
      title: '提示',
      content: '确定要删除选择的商品吗？',
      complete: async (res) => {
        if (res.cancel) {
          console.log("取消删除购物车");
        }
        if (res.confirm) {
          console.log("确定删除购物车");
          await deleteShippingCart(selectedShippingCartIds)
          // 加载购物车数据
          const index = that.data.activeIndex
          if (index === 0) {
            // 请求全部购物车数据
            await that.loadShippingCartList("all")
          } else {
            // 请求降价的购物车数据
            await that.loadShippingCartList("discount")
          }
          if (this.data.shippingCartSelectedList.length === 0) {
            this.setData({
              selectAll: false
            })
          }
        }
      }
    })

  },
  /**
   * 点击结算按钮
   */
  onTapCheckoutButton() {
    const selectedShippingCartList = this.data.shippingCartList.filter((cart, index) => {
      return this.data.shippingCartSelectedList[index] === true
    })
    if (selectedShippingCartList.length === 0) {
      Toast('您还没有选中要结算的商品');
      return
    }
    const products = selectedShippingCartList.map(cart => ({
      productSpecificationId: cart.productSpecificationId,
      quantity: cart.quantity
    }))
    const paramsStr = encodeURIComponent(JSON.stringify(products));
    wx.navigateTo({
      url: `/pages/OrderConfirmation/OrderConfirmation?params=${paramsStr}`,
    })
  },
  /**
   * 点击全选按钮
   */
  onTapSelectAll(event) {
    this.setData({
      selectAll: event.detail,
      shippingCartSelectedList: new Array(this.data.shippingCartSelectedList.length).fill(event.detail)
    })
    // 更改
    const selectedShippingCartList = this.data.shippingCartList.filter((cart, index) => {
      return this.data.shippingCartSelectedList[index] === true
    })
    const calculateRes = selectedShippingCartList.reduce((accumulator, currentItem) => {
      accumulator.totalQuantity += currentItem.quantity;
      accumulator.totalPrice += currentItem.discountPrice * currentItem.quantity;
      return accumulator;
    }, {
      totalQuantity: 0,
      totalPrice: 0
    })
    calculateRes.totalPrice = calculateRes.totalPrice.toFixed(2)
    this.setData({
      "selectedProductInfo.totalPrice": calculateRes.totalPrice,
      "selectedProductInfo.types": selectedShippingCartList.length,
      "selectedProductInfo.pieces": calculateRes.totalQuantity
    })
  },
  /**
   * 点击编辑按钮
   */
  onTapEditButton() {
    console.log('点击编辑按钮');
    this.setData({
      shippingCartStatus: this.data.shippingCartStatus === 0 ? 1 : 0,
      shippingCartSelectedList: new Array(this.data.shippingCartSelectedList.length).fill(this.data.selectAll ? true : false)
    })
  },
  /**
   *  点击控制面板区域
   */
  async onTapControlPanel(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      activeIndex: index
    })
    if (index === 0) {
      // 请求全部购物车数据
      await this.loadShippingCartList("all")
    } else {
      // 请求降价的购物车数据
      await this.loadShippingCartList("discount")
    }
  },
  /**
   * 修改购物车商品的商品数量
   */
  async onTapShippingCartStepper(event) {
    const shippingCartId = event.target.dataset.shippingCartId
    const quantity = event.detail
    await updateCartItemQuantity(shippingCartId, quantity)
    if (this.data.activeIndex === 0) {
      await this.loadShippingCartList("all")
    } else if (this.dataset.activeIndex === 1) {
      await this.loadShippingCartList("discount")
    }
  },
  /**
   * 进入商品详情页面
   */
  onTapNavigatorToProductPage(event) {
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${event.currentTarget.dataset.productId}`,
    })
  },
  /**
   * 加载购物车数据
   */
  async loadShippingCartList(option) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let res;
    if (option === "all") {
      res = await queryUserShippingCart()
    } else if (option === "discount") {
      res = await queryDiscountProducts()
    }
    this.setData({
      shippingCartList: res.data,
      shippingCartSelectedList: new Array(res.data.length).fill(false),
      selectAll: false,
      selectedProductInfo: {
        // 已选择商品的总价
        totalPrice: 0,
        // 已选择商品的总种类
        types: 0,
        // 已选择商品的总件数
        pieces: 0
      },
    })
    wx.hideLoading()
  },

  /**
   * 生命周期函数
   */
  async onShow() {
    console.log("购物车触发onShow方法");
    // 获取默认收获地址
    const address = await queryDefaultDeliveryAddress()
    this.setData({
      deliverAddress: address.data,
    })
    // 加载购物车数据
    const index = this.data.activeIndex
    console.log(index);
    if (index === 0) {
      // 请求全部购物车数据
      await this.loadShippingCartList("all")
    } else {
      // 请求降价的购物车数据
      await this.loadShippingCartList("discount")
    }

  },
  /**
   * 判断数组是否全为true
   */
  allTrue(arr) {
    return arr.every(item => item === true);
  }
})